#include "../TcpClass.h"
#include <pthread.h>
#define MAX_THREADNUM 2
pthread_t thread[MAX_THREADNUM];

void *my_thread(void *arg)
{
	TcpSocket tsock=*(TcpSocket*)arg;
	char filename[70];
	TcpSockRecv(&tsock,filename,sizeof(filename));
	printf("%s\n",filename);
	int file_fd = open(filename,O_RDWR|O_CREAT);
	printf("%d\n",file_fd);
	char buffer[1024];
	int size;
	unsigned long long sum = 0;
	while((size = TcpSockRecv(&tsock,buffer,sizeof(buffer))) > 0)
	{
		sum+=size;
		printf("size: %d\n",size);
		write(file_fd,buffer,size);
	}
	printf("sum: %llu\n",sum);
	TcpSockClose(&tsock);
	close(file_fd);
	printf("transport success\n");
	pthread_exit(NULL);
}

void thread_wait(void)
{	
	int i;
	for(i = 0;i<2;i++)
	{
		if(thread[i] !=0) 
		{ 
			pthread_join(thread[i],NULL);
		}
	}
}

void thread_init(void)
{
	int i;
	for(i = 0;i<2;i++)
	{
		memset(&thread[i], 0, sizeof(thread[i]));
	}
}

int main()
{
	thread_init();
	TcpServer ts;
    initTcpServer(&ts,"0.0.0.0",9999,5);
	int num=MAX_THREADNUM;
	while(num--)
	{
		TcpSocket tsock;
		TcpServAccept(&ts,&tsock);
		pthread_create(&thread[num-1], NULL, my_thread, &tsock);
	}
	thread_wait();
	return 0;
}
